package com.atguigu.gmall.common.interceptor.component;

import com.atguigu.gmall.cart.entity.UserAuth;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.common.util.ReqUtil;
import com.atguigu.gmall.user.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author:lyd
 * @Date:2023/9/4 19:39
 * @Version:1.0
 * @Description 用于判断用户是否处于登录状态
 **/
@Service
public class UserAuthComponent {

    @Autowired
   private  StringRedisTemplate redisTemplate;
    public  UserAuth getUserAuth() {
        HttpServletRequest request = ReqUtil.getOldRequest();
        UserAuth userAuth = new UserAuth();

        Cookie[] cookies = request.getCookies();
        //从cookie里面拿数据
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("userTempId".equalsIgnoreCase(name)) {
                    String userTempIdValue = cookie.getValue();
                    userAuth.setUserTempId(userTempIdValue);
                }
                if ("token".equalsIgnoreCase(name)) {
                    String tokenVale = cookie.getValue();
                    //判断这个token的值是否为空或者空字符串
                    if (StringUtils.hasText(tokenVale)) {
                        String jsonStr = redisTemplate.opsForValue().get(RedisConst.LOGIN_USER + tokenVale);
                        UserInfo userInfo = JSONs.jsonToObj(jsonStr, UserInfo.class);
                        userAuth.setUserId(userInfo.getId());
                    }
                }
            }
        }

        //从header中拿数据
        if (userAuth.getUserId() == null || !StringUtils.hasText(userAuth.getUserTempId())) {
            String token = request.getHeader("token");
            if (StringUtils.hasText(token)) {
                String jsonStr = redisTemplate.opsForValue().get(RedisConst.LOGIN_USER + token);
                UserInfo userInfo = JSONs.jsonToObj(jsonStr, UserInfo.class);
                userAuth.setUserId(userInfo.getId());
            }
            String userTempId = request.getHeader("userTempId");
            if (StringUtils.hasText(userTempId)) {
                userAuth.setUserTempId(userTempId);
            }
        }
        return userAuth;
    }

}
